# views.py
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import status
# 注册新用户
@api_view(['POST'])
def register(request):
    username = request.data.get('username')
    password = request.data.get('password')

    if User.objects.filter(username=username).exists():
        return JsonResponse({'message': '用户名已存在'}, status=400)

    user = User.objects.create(username=username, password=make_password(password))
    return JsonResponse({'message': '注册成功'}, status=201)

@api_view(['POST'])
def refresh_access_token(request):
    """
    刷新 access token
    """
    refresh_token = request.data.get('refreshToken')
    if not refresh_token:
        return Response({"detail": "Refresh token is required"}, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        # 通过 refresh token 获取新的 access token
        refresh = RefreshToken(refresh_token)
        new_access_token = str(refresh.access_token)
        return Response({"access_token": new_access_token})
    
    except Exception as e:
        return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)

# 用户登录
@api_view(['POST'])
def login(request):
    username = request.data.get('username')
    password = request.data.get('password')

    user = User.objects.filter(username=username).first()
    if not user or not check_password(password, user.password):
        return JsonResponse({'message': '用户名或密码错误'}, status=400)

    access_token = AccessToken.for_user(user)
    return JsonResponse({'access_token': str(access_token)}, status=200)

# 受保护的路由
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected(request):
    return JsonResponse({'message': '这是一个受保护的路由', 'user': request.user.username})